<style>
  .picImg {
    width: 40px;
    height: 40px;
  }
</style>
<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="infoTime" :model="infoTime" status-icon label-position="right"
               label-width="100px" style="display: flex">
        <el-form-item label="子公司名称" prop="subID">
          <el-select v-model="infoTime.subID" placeholder="子公司名称" style="width:100%">
            <el-option
              v-for="item in company"
              :key="item.subID"
              :label="item.subName"
              :value="item.subID">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker
            v-model="infoTime.startTime"
            type="datetime"
            placeholder="查询开始日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endTime">
          <el-date-picker
            v-model="infoTime.endTime"
            type="datetime"
            placeholder="查询结束日期"
            value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请选择状态" prop="status">
          <el-select v-model="infoTime.status" placeholder="请选择状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div style="margin-left: 30px">
          <el-button type="primary" @click="getList">查询</el-button>
        </div>
      </el-form>
    </div>
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row
              :header-cell-style="{background:'#92D3FF',color:'#fff'}">

      <!--<el-table-column fixed="" align="center" min-width="100" label="表单ID" prop="id"/>-->
      <el-table-column fixed="" align="center" min-width="100" label="表单编号" prop="formNo"/>
      <el-table-column align="center" min-width="120" label="保险公司名称" prop="suranceName"/>
      <el-table-column align="center" min-width="120" label="保代公司名称" prop="agentName"/>
      <el-table-column align="center" min-width="120" label="保理公司名称" prop="factoringName"/>
      <el-table-column align="center" min-width="100" label="上传时间" prop="addTime"/>
      <!--<el-table-column align="center" min-width="100" label="保单总数" prop="billCount"/>-->
      <el-table-column align="center" min-width="120" label="手续费总额 (元)" prop="amount"/>
      <el-table-column align="center" min-width="100" label="表单状态" prop="status" >
        <template slot-scope="scope">
          <span>{{scope.row.status | statusText }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" min-width="140" label="保代公司处理时间" prop="advanceTime"/>
      <el-table-column align="center" min-width="130" label="需要垫资保单数" prop="advanceCount"/>
      <el-table-column align="center" min-width="150" label="需要垫资金额 (元)" prop="advanceAmount"/>
      <el-table-column align="center" min-width="120" label="垫资支付时间" prop="advancePayTime"/>
      <el-table-column align="center" min-width="120" label="回款总额 (元)" prop="repayAmount"/>
      <el-table-column align="center" min-width="100" label="回款时间" prop="repayTime"/>
      <el-table-column align="center" min-width="130" label="垫资手续费 (元)" prop="interest"/>
      <el-table-column align="center" min-width="100" label="上传备注" prop="remarkUp"/>
      <el-table-column align="center" min-width="120" label="垫资申请备注" prop="remarkAdv"/>
      <el-table-column fixed="right" align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="success" size="mini"
                     @click="handleCheck(scope.row)">明细
          </el-button>
          <el-button v-if="[0,1,6].includes(scope.row.status)" type="primary" size="mini"
                     @click="handleClick(scope.row)">{{scope.row.status | buttonText}}
          </el-button>
          <!--<el-button type="success" size="mini" style="margin-top:6px;"
                     @click="bdagentfeeCheck(scope.row)">垫资回款确认
          </el-button>-->
          <el-popover
            v-if="scope.row.status==4"
            placement="top"
            width="200"
            trigger="manual"
            :ref="'popover-' + scope.row.id">
            <p>保险公司已回款，确定支付垫资与手续费给保里公司！</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="$refs[`popover-` + scope.row.id].doClose()">取消</el-button>
              <el-button type="primary" size="mini" @click="bdagentfeeCheck(scope.row)">确定</el-button>
            </div>
            <el-button type="primary" size="mini" slot="reference" @click="$refs[`popover-` + scope.row.id].doShow()"
            >垫资回款确认</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="infoTime.pageNum" :limit.sync="infoTime.pageSize"
                @pagination="getList"/>
    <el-dialog :visible.sync="editDialogVisible1" title="明细列表" width="800px" :close-on-click-modal="false">
      <el-table v-loading="listLoading1" :data="list1" element-loading-text="正在查询中。。。"
                border fit highlight-current-row :header-cell-style="{background:'#92D3FF',color:'#fff'}">

        <el-table-column align="center" min-width="100" label="保单号或合同号" prop="billNo"/>
        <el-table-column align="center" min-width="100" label="保单金额 (元)" prop="billAmount"/>
        <el-table-column align="center" min-width="100" label="代理手续费 (元)" prop="fee"/>
        <el-table-column align="center" min-width="100" label="代理人身份证号" prop="agentID"/>
        <el-table-column align="center" min-width="100" label="代理人编码" prop="agentNo"/>
        <!--<el-table-column align="center" min-width="100" label="是否需要垫资" prop="isAdvance">
          <template slot-scope="scope">{{{"0":"待确认","1":"不需要","2":"需要"}[scope.row.isAdvance]}} </template>
        </el-table-column>-->
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editDialogVisible1 = false">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editDialogVisible" title="表单垫支确认" :close-on-click-modal="false">
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" status-icon label-position="right"
               label-width="130px" style="width: 80%">
        <!--<el-form-item label="是否申请垫资" prop="allAdvance">
          <el-switch v-model="editForm.allAdvance"></el-switch>
        </el-form-item>-->
        <el-form-item label="备注">
          <el-input type="textarea" v-model="editForm.remark"></el-input>
        </el-form-item>
        <el-form-item label="垫资明细列表">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="string"
            :on-change="changeFile"
            :file-list="fileList"
            :limit="1"
            name="filename"
            :auto-upload="false">
            <el-button size="small" plain>选择文件</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xlsx(Excel2007)文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDone">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="editAccDialogVisible" title="账户选择" :close-on-click-modal="false">
      <el-form ref="editAccForm" :rules="editAccFormRules" :model="editAccForm" status-icon label-position="right"
               label-width="130px" style="width: 80%">
        <el-form-item label="保代公司账户" prop="account">
          <el-select v-model="editAccForm.account" placeholder="请选择一个保代公司账户">
            <el-option
              v-for="item in accountList"
              :key="item.id"
              :label="item.accName"
              :value="item.account">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editAccDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handlePayDone">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {doGet, doPost, doFile} from '@/api'
  import {cities} from '@/utils/base'
  import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

  const FETCH_PAGE = 'bdagentfee.html'
  const FETCH_URL = {
    LIST: `${FETCH_PAGE}?op=list`,
    CREATE: `${FETCH_PAGE}?op=billlist`,
    EDIT: `${FETCH_PAGE}?op=formup`,
    DELETE: `${FETCH_PAGE}?op=formreup`,
    IMPORT: `${FETCH_PAGE}?op=interest`,
    PAY: `${FETCH_PAGE}?op=pay`
  }
  export default {
    name: 'bdagentfee',
    components: {Pagination},
    filters: {
      buttonText(status) {
        let text = undefined
        switch (status) {
          case 0:
            text = '申请垫资';
            break
          case 1:
            text = '重新申请垫资';
            break
          /*case 4:
            text = '支付垫资利息';*/
            break
          case 6:
            text = '余额提款';
            break
          default:
            text = '';
            break
        }
        return text
      },
      statusText(status) {
        let text = undefined
        switch (status) {
          case 0:
            text = '表单已上传';
            break
          case 1:
            text = '保代公司垫资已申请';
            break
          case 2:
            text = '保理公司已接收';
            break
          case 3:
            text = '保理公司垫资已支付';
            break
          case 4:
            text = '保险公司已回款';
            break
          case 5:
            text = '垫资利息已支付';
            break
          case 6:
            text = '垫资利息已支付';
            break
          case 7:
            text = '保代公司已取款';
            break
          default:
            text = '';
            break
        }
        return text
      }
    },
    data() {
      return {
        options: [{
          value: '',
          label: '请选择状态'
        }, {
          value: '0',
          label: '表单已上传'
        }, {
          value: '1',
          label: '保代公司垫资已申请'
        }, {
          value: '2',
          label: '保理公司已接收'
        }, {
          value: '3',
          label: '保理公司垫资已支付'
        }, {
          value: '4',
          label: '保险公司已回款'
        }, {
          value: '6',
          label: '垫资利息已支付'
        }, {
          value: '7',
          label: '保代公司已取款'
        }],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }]
        },
        list: [],
        list1:[],
        total: 0,
        listLoading: true,
        listLoading1: true,
        infoTime:{
          startTime:undefined,
          endTime:undefined,
          status:undefined,
          pageNum: 1,
          pageSize: 20,
          subID: undefined
        },
        editForm: {
          allAdvance: undefined,
          remark: undefined,
          billFile: undefined
        },
        editFormRules: {
          allAdvance: [{required: true, message: '请选择是否申请垫资', trigger: 'blur'}]
        },
        editDialogVisible: false,
        editDialogVisible1: false,
        fileList: [],
        id: undefined,
        editAccDialogVisible: false,
        editAccForm: {
          account: undefined
        },
        editAccFormRules: {
          account: [{required: true, message: '请选择提款账户', trigger: 'blur'}]
        },
        accountList: [],
        company: []
      }
    },
    created() {
      this.getList()
      this.getCompanyList()
    },
    methods: {
      getCompanyList() {
        doGet('insuragent.html?op=getSubList', {}) .then(response => {
          this.company = response.rows
        })
          .catch(response => {
            this.company = []
          })
      },
      getList() {
        this.listLoading = true;
        doGet(FETCH_URL.LIST, this.infoTime).then(response => {
          this.list = response.rows;
          this.total = response.data.totalcount;
          this.listLoading = false
        }).catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false
        })
      },
      handleCheck(row) {
        this.list1 = [];
        this.editDialogVisible1 = true
        this.listLoading1=true
//        console.log(row.id)
        doGet(FETCH_URL.CREATE, {id:row.id}).then(response => {
          this.list1=response.rows
//          console.log(response.rows);
          this.listLoading1=false
//          this.editForm.id = response.rows[0].id;
//          this.editForm.billNo = response.rows[0].billNo;
//          this.editForm.billAmount = response.rows[0].billAmount;
//          this.editForm.fee = response.rows[0].fee;
//          this.editForm.unicode = response.rows[0].unicode;
//          this.editForm.isAdvance = response.rows[0].isAdvance
        }).catch(() => {
          this.list1 = [];
          this.total = 0;
          this.listLoading1=false
        })
      },

      handleClick(row) {

        this.id = row.id
        if (row.status == 0 || row.status == 1) {
          Object.keys(this.editForm).forEach(item => {
            if (item == 'allAdvance') {
              this.editForm[item] = false
            } else {
              this.editForm[item] = undefined
            }
          })
          this.editDialogVisible = true
          this.$nextTick(() => {
            this.$refs['editForm'].clearValidate()
          })
        } else if (row.status == 6) {
          this.editAccForm.account = undefined
          this.editAccDialogVisible = true
          this.$nextTick(() => {
            this.$refs['editAccForm'].clearValidate()
          })
          this.accountList = []
          doGet('insuragent.html?op=acclist', {id: row.insuragentID}).then(response => {
            this.accountList = response.rows
          }).catch(response => {
            this.accountList = []
          })
        }
      },


      // 选择文件
      changeFile(file) {
        console.log('before upload')
        console.log(file)
        this.fileList = [file]
        let extension = file.name.substring(file.name.lastIndexOf('.')+1)
        let size = file.size / 1024 / 1024
        if(extension !== 'xlsx'&&extension !== 'xls') {
          this.$notify.warning({
            title: '警告',
            message: `只能上传Excel（即后缀是.xlsx或.xls）的文件`
          });
          this.fileList = []
        }
      },

      // 申请垫支
      handleDone() {
        this.$refs['editForm'].validate(valid => {
          if (valid) {
            let status = this.list.filter(item => {
              return item.id == this.id
            })[0].status
            let fetchUrl = status == 0 ? FETCH_URL.EDIT : FETCH_URL.DELETE
            this.editForm.allAdvance = this.editForm.allAdvance ? 1 : 0
            let fd = new FormData()
            fd.append('billFile', this.fileList[0])
            fd.append('allAdvance', this.editForm.allAdvance)
            fd.append('id', this.id)
            fd.append('remark', this.editForm.remark)
            doFile(fetchUrl, fd).then(response => {
              this.getList()
              this.editDialogVisible = false
              this.$notify.success({
                title: '成功',
                message: '申请垫支成功'
              })
            }).catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.message
              })
            })
          }
        })
      },
        bdagentfeeCheck(row) {
          this.advance = {
              id: row.id,
              advanceAmount: row.advanceAmount
          }
            doGet('bdagentfee.html?op=confirAdvance', this.advance).then(response => {
                this.getList()
                this.$notify.success({
                    title: '成功',
                    message: '垫资回款成功'
                })
            }).catch(response => {
                this.$notify.error({
                    title: '失败',
                    message: response.message
                })
            })
        },
      // 表单垫资利息支付
      /*payInterest() {
        doGet(FETCH_URL.IMPORT, {id: this.id}).then(response => {
          this.getList()
          this.$notify.success({
            title: '成功',
            message: '支付成功'
          })
        }).catch(response => {
          this.$notify.error({
            title: '失败',
            message: response.message
          })
        })
      },*/

      // 提款
      handlePayDone() {
        this.$refs['editAccForm'].validate(valid => {
          if (valid) {
            doGet(FETCH_URL.PAY, {id: this.id, account: this.editAccForm.account}).then(response => {
              this.getList()
              this.editAccDialogVisible = false
              this.$notify.success({
                title: '成功',
                message: '提款成功'
              })
            }).catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.message
              })
            })
          }
        })


      }
    }
  }
</script>
